

//
//  CPJEmoticonModel.swift
//  Sina
//
//  Created by YYY on 2017/8/29.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class CPJEmoticonModel: NSObject {

    //表情类型 （false：图片表情，true：文字表情）
    var type = false
    
    //表情图片名称
    var png: String?
    
    //发给新浪微博服务器的表情文字，节省流量
    var chs: String?
    
    //emoji字符串
    var emoji: String?
    
    //emoji的十六进制编码
    var code: String?
    {
        didSet
        {
            guard let code = code else
            {
                return
            }
            let scanner = Scanner(string: code)
            
            var result: UInt32 = 0
            
            scanner.scanHexInt32(&result)
            
            emoji = String(Character(UnicodeScalar(result)!))
        }
    }
    
    //所在目录
    var directory: String?
    
    //图片表情对应的图像
    var image: UIImage?
    {
        if type
        {
            return nil
        }
        guard let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil),
            let bundle = Bundle(path: path),
            let directory = directory,
            let png = png
            else
        {
            return nil
        }
        let imageObj = UIImage(named: "\(directory)/\(png)", in: bundle, compatibleWith: nil)
        
        return imageObj
    }
    
    //将图像转换生成图片的属性文本
    func imageText(font: UIFont) -> NSAttributedString
    {
        //判读图像是否存在
        guard let image = image else
        {
            return NSAttributedString(string: "")
        }
        
        //创建文本附件
        let attachment = EmoticonAttachment()
        attachment.chs = chs
        attachment.image = image
        let height = font.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)
        
        //返回图片属性文本
        
        let attributeMutable = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        attributeMutable.addAttributes([NSFontAttributeName: font], range: NSRange(location: 0, length: 1))
        return attributeMutable
    }
    override var description: String
    {
        return yy_modelDescription()
    }
    
}
